<template >
    <a-spin :spinning="spinning" tip="Loading">
        <a-row type="flex" justify="left" align="middle">
            <a-col :xs="{ span: 12, offset: 6 }" :sm="{ span: 12, offset: 6 }" :md="{ span: 12, offset: 6 }" :lg="{ span: 12, offset: 6 }"
                :xl="{ span: 12, offset: 6 }">
                <a-input-search id="dom_map.author_search.search" v-model:value="searchQuery" placeholder="请输入完整或部分关键词"
                    style="height: 4vh;margin-top: 4vh;" onfocus="this.placeholder=''"
                    onblur="this.placeholder='请输入完整或部分关键词'" enter-button size="large" @search="onSearch">
                    <template v-slot:addonBefore>
                        <a-select style="height: 4vh" defaultValue="author" :options="options"
                            @change="handleSelectChange"></a-select>
                    </template>
                </a-input-search>
            </a-col>
        </a-row>
        <a-divider />
        <a-row type="flex" justify="left" align="middle">
            <a-col :xs="{ span: 20, offset: 4 }" :sm="{ span: 20, offset: 4 }" :md="{ span: 20, offset: 4 }" :lg="{ span: 20, offset: 4 }"
                :xl="{ span: 20, offset: 4 }">
                <a-row type="flex" align="top" style="margin: 10px">
                    <a-col :xs="{ span: 4 }" :sm="{ span: 4 }" :md="{ span: 4 }" :lg="{ span: 4 }" :xl="{ span: 4 }">
                        <div style="display: table; vertical-align: middle">
                            <p style="display: table-cell">
                                <a-typography-text><strong>共找到{{ pagination.total }}个作者</strong></a-typography-text>
                            </p>
                        </div>
                    </a-col>
                </a-row>
            </a-col>
        </a-row>
        <a-row>
            <a-col :xs="{ span: 16, offset: 4 }" :sm="{ span: 16, offset: 4 }" :md="{ span: 16, offset: 4 }" :lg="{ span: 16, offset: 4 }"
                :xl="{ span: 16, offset: 4 }">
                <!-- 列表展示作者查询结果 -->
                <a-list item-layout="vertical" size="large" style="background: '#fff';margin-bottom: 4vh;" :pagination="pagination"
                    :data-source="authorDisplay" :split="false" :grid="{ column: 1 }">
                    <template #footer>
                        <div>
                            The recommendation is based on our model, Shenyang The One Rec.
                        </div>
                    </template>
                    <template #renderItem="{ item }">
                        <a-list-item :key="item.author_id" text-overflow="ellipsis">
                            <a-card hoverable :bordered="true"
                                @click="$router.push('/author_info?author_id=' + item.author_id)">
                                <a-row>
                                    <a-col :xs="{ span: 2 }" :sm="{ span: 2 }" :md="{ span: 2 }" :lg="{ span: 2 }"
                                        :xl="{ span: 2 }">
                                        <div>
                                            <a-avatar shape="square" size={64}
                                                src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
                                            <!-- :src="item.url"  -->
                                        </div>
                                    </a-col>
                                    <a-col :xs="{ span: 17 }" :sm="{ span: 17 }" :md="{ span: 17 }" :lg="{ span: 17 }"
                                        :xl="{ span: 17 }">
                                        <a-card-meta :title="item.author_name"><!-- 作者姓名、国际 -->
                                            <div v-if="highlightField === 'title'">
                                                <span v-html="highlight(item.author_name)"></span>
                                            </div>
                                            <div v-else>
                                                {{ item.author_name }}
                                            </div>
                                        </a-card-meta>
                                        <br>
                                        <div style="color:#acadae" slot="description"><icon-font
                                                type="icon-weizhi"></icon-font> {{ "中国" }}</div>
                                        <!-- item.author_nationality -->
                                        <div style="color:#66aef5" slot="description"><icon-font
                                                type="icon-xuewei"></icon-font> {{ "生命科学" }}</div>
                                        <!-- item.domain -->
                                        <!-- <a-card-meta :description="item.domain"></a-card-meta> -->
                                        <!-- 作者从事的领域 -->
                                    </a-col>
                                    <a-col :xs="{ span: 3, offset: 1 }" :sm="{ span: 3, offset: 1 }" :md="{ span: 3, offset: 1 }"
                                        :lg="{ span: 3, offset: 1 }" :xl="{ span: 3, offset: 1 }"><!-- 作者文章的引用次数 -->
                                        <a-row justify="end">
                                            <div style="font-size:2.2em;color:#a31be8;font-weight: bold; ">{{
                                                NumFormat(item.cite_num ) }}</div>
                                            <!--  NumFormat(item.cite_num ) -->
                                        </a-row>
                                        <br>
                                        <a-row justify="end">
                                            <div style="font-size:1.3em;color:#1a045a">被引用次数</div>
                                        </a-row>
                                    </a-col>
                                </a-row>
                            </a-card>
                        </a-list-item>
                    </template>
                </a-list>
            </a-col>
        </a-row>
    </a-spin>
</template>

    

<script>
import { defineComponent, onMounted, reactive, toRefs, ref } from 'vue'
import { StarOutlined, StarFilled, FilePdfOutlined, BulbOutlined, createFromIconfontCN } from '@ant-design/icons-vue'
import { search_author } from '@/api/post/search_author'
import { cloneDeep } from 'lodash-es'
import { icon_url } from '@/util/iconfont'
import dom_map from '@/constant/dom_map'
import globalVariable from '@/components/mathJax/globalVariable'
import ListItem from '@/components/card_components/ListItem'
import '@vuepic/vue-datepicker/dist/main.css'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'

const IconFont = createFromIconfontCN({
    scriptUrl: icon_url


});

export default defineComponent({
    components: {
        StarOutlined,
        StarFilled,
        FilePdfOutlined,
        BulbOutlined,
        IconFont,
        ListItem,
    },

    setup() {
        const state = reactive({
            searchQuery: '',                // 搜索词
            searchField: 'author',           // 搜索范围，默认初始为标题
            loading: false,                 // 加载状态
            highlightText: '',               // 高亮词，和searchQuery区分防止在输入后触发
            highlightField: '',              // 同上，防止切换searchField之后直接触发高亮转换
            options: [
                { label: '按标题', value: 'title' },
                { label: '按摘要', value: 'abstract' },
                { label: '按作者', value: 'author' },
            ],
            authorList: [],                  // 作者列表
            authorDisplay: [],               // 展示作者列表

            pagination: {
                //分页设置
                simple: true,
                defaultCurrent: 1,
                current: 1,
                defaultPageSize: 8,
                total: 0,
                onChange: (current) => {
                    state.loading = true
                    state.pagination.defaultCurrent = current
                    state.pagination.current = current
                    update()
                    console.log("应该后发生")
                    spinning.value = true
                },
            },
        })

        onBeforeRouteLeave((to, from, next) => {
            // 在这里处理页面离开的逻辑
            if (from.meta.keepAlive) {
                let accessTime = 1
                if (sessionStorage.getItem($route.fullPath + 'accessTime') != null) {
                    accessTime = parseInt(sessionStorage.getItem($route.fullPath + 'accessTime'))
                    accessTime += 1
                }
                let _data = Object.assign(state.pagination, {})
                sessionStorage.setItem($route.fullPath + 'nowPageData' + accessTime, JSON.stringify(_data))
                sessionStorage.setItem($route.fullPath + 'nowSearchQuery' + accessTime, JSON.stringify(state.searchQuery))
                sessionStorage.setItem($route.fullPath + 'searchField' + accessTime, JSON.stringify(state.searchField))
                sessionStorage.setItem($route.fullPath + 'authorList' + accessTime, JSON.stringify(state.authorList))
                sessionStorage.setItem($route.fullPath + 'authorDisplay' + accessTime, JSON.stringify(state.authorDisplay))
                sessionStorage.setItem($route.fullPath + 'accessTime', JSON.stringify(accessTime))
                sessionStorage.setItem($route.fullPath + 'randomId' + accessTime, JSON.stringify(route.query.randomId))
            }
            next()
        })


        const spinning = ref(true)
        async function update() {

            // 调用搜索接口
            await search_author(state.searchQuery, state.defaultPageSize, state.pagination.defaultCurrent, state.searchField).then(async (response) => {
                spinning.value = true
                if (response.data.status.code === 0) {
                    // 请求成功
                    state.pagination.total = response.data.data.total
                    state.authorList = response.data.data.authorList
                    state.authorDisplay = cloneDeep(state.authorList)
                    state.highlightText = state.searchQuery
                    state.highlightField = state.searchField
                }
                spinning.value = false
            })
            console.log("应该先发生")
            await checkLaTex()

        }



        const checkLaTex = () => {
            globalVariable.initMathjaxConfig();
            globalVariable.MathQueue();
        }

        const updateSearch = () => {
            state.pagination.onChange(1)
        }
        const route = useRoute()
        const router = useRouter()
        const $route = useRoute();

        //模拟调用假接口传入表格数据
        onMounted(() => {
            if (sessionStorage.getItem($route.fullPath + 'accessTime') != null) {
                let accessTime = parseInt(sessionStorage.getItem($route.fullPath + 'accessTime'));
                if (route.query.randomId === JSON.parse(sessionStorage.getItem($route.fullPath + 'randomId' + accessTime))) {
                    spinning.value = true
                    let _obj = JSON.parse(sessionStorage.getItem($route.fullPath + 'nowPageData' + accessTime));
                    state.pagination.simple = _obj.simple
                    state.pagination.current = _obj.current
                    state.pagination.defaultCurrent = _obj.defaultCurrent
                    state.pagination.total = _obj.total
                    state.searchQuery = JSON.parse(sessionStorage.getItem($route.fullPath + 'nowSearchQuery' + accessTime));
                    state.searchField = JSON.parse(sessionStorage.getItem($route.fullPath + 'searchField' + accessTime));
                    state.authorList = JSON.parse(sessionStorage.getItem($route.fullPath + 'authorList' + accessTime));
                    state.authorDisplay = JSON.parse(sessionStorage.getItem($route.fullPath + 'authorDisplay' + accessTime));
                    sessionStorage.removeItem($route.fullPath + 'nowPageData' + accessTime);
                    sessionStorage.removeItem($route.fullPath + 'nowSearchQuery' + accessTime);
                    sessionStorage.removeItem($route.fullPath + 'searchField' + accessTime);
                    sessionStorage.removeItem($route.fullPath + 'authorList' + accessTime);
                    sessionStorage.removeItem($route.fullPath + 'randomId' + accessTime);
                    sessionStorage.removeItem($route.fullPath + 'authorDisplay' + accessTime);
                    if (accessTime == 1) sessionStorage.removeItem($route.fullPath + 'accessTime')
                    else {
                        sessionStorage.setItem($route.fullPath + 'accessTime', JSON.stringify(accessTime - 1))
                    }
                    spinning.value = false
                } else {

                    state.searchQuery = route.query.searchQuery
                    update()
                }
            }
            else {
                state.searchQuery = route.query.searchQuery
                update()
            }

        })



        const onSearch = () => {

            if (state.searchField != "author") {
                router.push('/homepage?searchQuery=' + state.searchQuery + '&&searchField=' + state.searchField + '&&randomId=' + Math.random())
            }
            else {
                // 搜索操作更新论文列表
                if (state.searchQuery.length === 0) {
                    // 没有搜索内容时恢复原状
                    state.authorDisplay = state.authorList
                }
                let from
                // 丢弃先前的搜索结果
                if (state.authorList.length !== state.authorDisplay.length) {
                    from = state.authorList
                } else {
                    from = state.authorDisplay
                }
                updateSearch()
                // 设置spinning的代码逻辑与分页相同
                spinning.value = true
            }
        }

        //搜索类型切换
        const handleSelectChange = (value) => {
            state.searchField = value
        }

        const highlight = (content) => {
            if (!state.highlightText || state.highlightText == '') return content
            let index = 0
            let parts = []
            while (index < content.length) {
                //全部转换为小写后比较
                let nextIndex = content.toLowerCase().indexOf(state.highlightText.toLowerCase(), index)
                if (nextIndex === -1) {
                    parts.push(content.slice(index))
                    break
                }
                if (nextIndex > index) {
                    parts.push(content.slice(index, nextIndex))
                }
                //复原字符串时按照content中的大小写进行拼接
                let matchCase = ''
                for (let i = 0; i < state.highlightText.length; i++) {
                    matchCase += content.charAt(nextIndex + i)
                }
                parts.push(matchCase)
                index = nextIndex + state.highlightText.length
            }
            console.log(parts)
            return parts.map((part) => {
                if (part.toLowerCase() === state.highlightText.toLowerCase()) {
                    return '<span style="background-color:yellow">' + part + '</span>'
                } else {
                    return part
                }

            }).join('')
        }
        //数字实现三个为一组分隔开
        const NumFormat = (value) => {
            if (!value) return 0
            value = value.toFixed(2)
            var intPart = Math.trunc(value)// 获取整数部分
            var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
            return intPartFormat
        }

        return {
            ListItem,
            ...toRefs(state),
            onSearch,
            highlight,
            handleSelectChange,
            NumFormat,
            spinning,
            dom_map,
            route,
            router
        };
    },
});
</script>


<style scoped lang="scss">
.ul_list {
    margin: 0;
    padding: 0;

    li {
        list-style: none;
        border-radius: 8px;
        display: flex;
        overflow: hidden;
    }

}

//button背景
:deep(.ant-btn-primary) {
    color: #fff;
    border-color: #59baff;
    background: #59baff;

}

.ant-card {
    font-size: 1em;
    line-height: 1.55;
    background: #fafdff;
    border-radius: 5px;
}

//头像
.ant-avatar {
    width: 7vh;
    height: 9vh;
}</style>



